package com.ychen.user.controller;

import com.ychen.commons.entity.user.UserEntity;
import com.ychen.commons.utils.JwtUtils;
import com.ychen.commons.utils.R;
import com.ychen.user.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @ Author     ：ChenYuliao
 * @ Date       ：Created in 23:34 2018/9/18 0018
 * @ Description：
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Value("${jwt.app.secret}")
    private String secret;

    //12小时后过期
    @Value("${jwt.app.expire}")
    private Long expire;


    @ApiOperation(value = "用户登录", notes = "用户登录note")
    @PostMapping("/login")
    public R login(@RequestBody Map<String, Object> params, HttpServletResponse response) {
        String uniqueString = (String) params.get("uniqueString");
        String password = (String) params.get("password");
        UserEntity userEntity = userService.checkUserByUnique(uniqueString);
        if (userEntity != null && password.equals(userEntity.getPassword())) {
            //登陆成功
            String token = JwtUtils.generateToken(userEntity.getUserId(), "USER_" + userEntity, expire, secret);
            response.setHeader("token", token);
            Cookie cookie = new Cookie("token", token);
            response.addCookie(cookie);

            return R.ok().put("userInfo", userEntity).put("token", token);
        }
        return R.error(1, "用户名或密码错误");

    }


}
